package com.heima.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author mgw
 * @create 2021/9/26 22:46
 */
@RestController
@RequestMapping("/dfs")
public class DfsController {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), StringUtils.getFilenameExtension(file.getOriginalFilename()),
                null);
        String url= fdfsWebServer.getWebServerUrl()+ storePath.getFullPath();
        return ResponseResult.okResult(url);
    }
    @PostMapping("/html/upload")
    public ResponseResult uploadHtml(@RequestParam String content) throws IOException {
        //将文件转换为输入流
        byte[] bytes = content.getBytes();
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        StorePath storePath = fastFileStorageClient.uploadFile(is, bytes.length,"html",null);
        String url= fdfsWebServer.getWebServerUrl()+ storePath.getFullPath();
        return ResponseResult.okResult(url);
    }

    /***
     * 文件下载方法
     * List<String> urls图片地址   http://192.168.211.136/group1/M00/00/01/xxx.jpg
     * return List<byte[]>
     */
    @PostMapping(value = "/list/download")
    public List<byte[]> download(@RequestParam List<String> images) throws Exception {
        List<byte[]> imageBytes = new ArrayList<byte[]>();
        for (String image : images) {
            if(image.startsWith("http://")){
                image=image.replace(fdfsWebServer.getWebServerUrl()+"group1/","");
            }
            byte[] bytes = fastFileStorageClient.downloadFile("group1", image, new DownloadByteArray());
            imageBytes.add(bytes);
        }
        return imageBytes;
    }
}
